/**
 * System App 主题管理器
 * 监听主应用的主题变化并同步到本应用
 */

import { ElMessage } from 'element-plus';

// 主题状态接口
interface ThemeState {
  isDark: boolean;
  themeName: string;
  timestamp: number;
}

// 主题管理器类
class SystemAppThemeManager {
  private static instance: SystemAppThemeManager;
  private currentTheme: ThemeState | null = null;
  private listeners: Set<(theme: ThemeState) => void> = new Set();
  private isInitialized = false;

  private constructor() {
    this.init();
  }

  static getInstance(): SystemAppThemeManager {
    if (!SystemAppThemeManager.instance) {
      SystemAppThemeManager.instance = new SystemAppThemeManager();
    }
    return SystemAppThemeManager.instance;
  }

  // 初始化主题管理器
  private init(): void {
    if (this.isInitialized) {
      return;
    }

    console.log('[SystemAppThemeManager] 初始化主题管理器');

    // 监听主应用的主题变化消息
    this.setupMessageListener();

    // 监听postMessage事件（兼容模式）
    this.setupPostMessageListener();

    // 监听DOM事件
    this.setupDOMEventListener();

    this.isInitialized = true;
  }

  // 设置消息监听器
  private setupMessageListener(): void {
    // 如果存在全局消息服务，使用它
    if (window.$messageService) {
      console.log('[SystemAppThemeManager] 使用消息服务监听主题变化');
      
      window.$messageService.onMessage('THEME_CHANGE', (message) => {
        console.log('[SystemAppThemeManager] 接收到主题变化消息:', message);
        this.handleThemeChange(message.data);
      });

      window.$messageService.onMessage('GLOBAL_STATE_CHANGE', (message) => {
        if (message.data && message.data.theme !== undefined) {
          console.log('[SystemAppThemeManager] 从全局状态变化检测到主题:', message.data.theme);
          this.handleThemeChange({
            isDark: message.data.theme === 'dark',
            themeName: message.data.theme,
            timestamp: Date.now()
          });
        }
      });
    }
  }

  // 设置postMessage监听器
  private setupPostMessageListener(): void {
    window.addEventListener('message', (event) => {
      try {
        if (event.data && event.data.type === 'THEME_CHANGE') {
          console.log('[SystemAppThemeManager] 接收到postMessage主题变化:', event.data.payload);
          this.handleThemeChange(event.data.payload);
        }
      } catch (error) {
        console.warn('[SystemAppThemeManager] 处理postMessage事件失败:', error);
      }
    });
  }

  // 设置DOM事件监听器
  private setupDOMEventListener(): void {
    // 监听自定义事件
    window.addEventListener('theme-changed', (event: any) => {
      console.log('[SystemAppThemeManager] 接收到主题变化事件:', event.detail);
      this.handleThemeChange(event.detail);
    });

    // 监听storage事件（主题状态持久化）
    window.addEventListener('storage', (event) => {
      if (event.key === 'micro-app-theme-state' && event.newValue) {
        try {
          const themeState = JSON.parse(event.newValue);
          console.log('[SystemAppThemeManager] 从localStorage检测到主题变化:', themeState);
          this.handleThemeChange(themeState);
        } catch (error) {
          console.warn('[SystemAppThemeManager] 解析主题状态失败:', error);
        }
      }
    });
    
    // 监听微应用重新挂载事件
    window.addEventListener('micro-app-remount', (event: any) => {
      console.log('[SystemAppThemeManager] 接收到微应用重新挂载事件:', event.detail);
      // 重新应用当前主题
      if (this.currentTheme) {
        console.log('[SystemAppThemeManager] 重新应用当前主题');
        this.applyTheme(this.currentTheme);
      }
    });
  }

  // 处理主题变化
  private handleThemeChange(themeState: ThemeState): void {
    console.log('[SystemAppThemeManager] 处理主题变化:', themeState);
    
    if (!themeState || !themeState.themeName) {
      console.warn('[SystemAppThemeManager] 无效的主题状态');
      return;
    }

    // 检查是否真的是主题变化
    if (this.currentTheme && 
        this.currentTheme.isDark === themeState.isDark && 
        this.currentTheme.themeName === themeState.themeName) {
      console.log('[SystemAppThemeManager] 主题未变化，跳过处理');
      return;
    }

    this.currentTheme = themeState;
    
    // 应用主题到应用
    this.applyTheme(themeState);
    
    // 通知所有监听器
    this.notifyListeners(themeState);
    
    // 显示提示
    ElMessage.success(`主题已切换至: ${themeState.themeName === 'dark' ? '深色模式' : '浅色模式'}`);
  }

  // 应用主题到应用
  private applyTheme(themeState: ThemeState): void {
    const { isDark, themeName } = themeState;
    
    console.log(`[SystemAppThemeManager] 应用主题: ${themeName}`);

    // 1. 切换HTML的class
    const html = document.documentElement;
    if (isDark) {
      html.classList.add('dark');
      html.classList.remove('light');
    } else {
      html.classList.add('light');
      html.classList.remove('dark');
    }

    // 2. 切换Element Plus的主题
    // Element Plus会自动根据html的dark类切换主题
    
    // 3. 应用CSS变量
    this.applyCSSVariables(isDark);

    // 4. 触发自定义事件，供其他组件监听
    window.dispatchEvent(new CustomEvent('system-app-theme-applied', {
      detail: themeState
    }));
  }

  // 应用CSS变量
  private applyCSSVariables(isDark: boolean): void {
    const root = document.documentElement;
    
    if (isDark) {
      // 深色模式变量
      root.style.setProperty('--el-bg-color', '#141414');
      root.style.setProperty('--el-text-color-primary', '#ffffff');
      root.style.setProperty('--el-text-color-regular', '#e4e7ed');
      root.style.setProperty('--el-border-color', '#303030');
      root.style.setProperty('--el-fill-color-blank', '#1e1e1e');
      root.style.setProperty('--el-fill-color-light', '#262727');
      root.style.setProperty('--el-color-primary-light-9', '#162b45');
      root.style.setProperty('--el-menu-bg-color', '#141414');
      root.style.setProperty('--el-menu-text-color', '#ffffff');
      root.style.setProperty('--el-menu-active-color', '#409eff');
    } else {
      // 浅色模式变量（使用默认值）
      root.style.removeProperty('--el-bg-color');
      root.style.removeProperty('--el-text-color-primary');
      root.style.removeProperty('--el-text-color-regular');
      root.style.removeProperty('--el-border-color');
      root.style.removeProperty('--el-fill-color-blank');
      root.style.removeProperty('--el-fill-color-light');
      root.style.removeProperty('--el-color-primary-light-9');
      root.style.removeProperty('--el-menu-bg-color');
      root.style.removeProperty('--el-menu-text-color');
      root.style.removeProperty('--el-menu-active-color');
    }
  }

  // 通知所有监听器
  private notifyListeners(themeState: ThemeState): void {
    this.listeners.forEach(listener => {
      try {
        listener(themeState);
      } catch (error) {
        console.warn('[SystemAppThemeManager] 通知监听器失败:', error);
      }
    });
  }

  // 添加主题变化监听器
  public addThemeListener(callback: (theme: ThemeState) => void): () => void {
    this.listeners.add(callback);
    
    // 如果已有主题状态，立即通知
    if (this.currentTheme) {
      callback(this.currentTheme);
    }
    
    // 返回取消监听的函数
    return () => {
      this.listeners.delete(callback);
    };
  }

  // 获取当前主题
  public getCurrentTheme(): ThemeState | null {
    return this.currentTheme;
  }

  // 手动切换主题（用于测试）
  public switchTheme(isDark: boolean): void {
    const themeState: ThemeState = {
      isDark,
      themeName: isDark ? 'dark' : 'light',
      timestamp: Date.now()
    };
    
    this.handleThemeChange(themeState);
  }

  // 从主应用获取当前主题状态
  public async fetchThemeFromMainApp(): Promise<void> {
    try {
      // 方法1: 通过全局状态获取
      if (window.$getGlobalState) {
        const globalState = window.$getGlobalState();
        if (globalState && globalState.theme) {
          console.log('[SystemAppThemeManager] 从全局状态获取主题:', globalState.theme);
          this.handleThemeChange({
            isDark: globalState.theme === 'dark',
            themeName: globalState.theme,
            timestamp: Date.now()
          });
          return;
        }
      }

      // 方法2: 通过消息服务请求主题状态
      if (window.$messageService) {
        console.log('[SystemAppThemeManager] 请求主题状态...');
        window.$messageService.broadcast('REQUEST_THEME_STATE', {});
      }

      // 方法3: 从localStorage获取
      const storedTheme = localStorage.getItem('micro-app-theme-state');
      if (storedTheme) {
        const themeState = JSON.parse(storedTheme);
        console.log('[SystemAppThemeManager] 从localStorage获取主题:', themeState);
        this.handleThemeChange(themeState);
      }
    } catch (error) {
      console.warn('[SystemAppThemeManager] 获取主题状态失败:', error);
    }
  }
}

// 创建全局实例
export const systemAppThemeManager = SystemAppThemeManager.getInstance();

// 便捷函数
export const useSystemAppTheme = () => {
  return systemAppThemeManager;
};

// 主题切换函数（供主应用调用）
export const switchTheme = (isDark: boolean): void => {
  systemAppThemeManager.switchTheme(isDark);
};

// 初始化主题（在应用启动时调用）
export const initSystemAppTheme = async (): Promise<void> => {
  await systemAppThemeManager.fetchThemeFromMainApp();
};

export default systemAppThemeManager;